package com.yue92.datalife.config;

import com.yue92.datalife.common.DatabaseContextHolder;
import com.yue92.datalife.common.DynamicDataSource;
import com.zaxxer.hikari.HikariDataSource;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {

    @Configuration
    @ConfigurationProperties(prefix = "datasource.master")
    @Getter
    @Setter
    public static class MasterProperties {

        private String url;

        private String username;

        private String password;

    }

    @Configuration
    @ConfigurationProperties(prefix = "datasource.slave")
    @Getter
    @Setter
    public static class SlaveProperties {

        private String url;

        private String username;

        private String password;

    }

    @Bean
    public DataSource dynamicDataSource(MasterProperties masterProperties, SlaveProperties slaveProperties)
    {
        HikariDataSource dataSourceMaster = new HikariDataSource();
        dataSourceMaster.setJdbcUrl(masterProperties.getUrl());
        dataSourceMaster.setUsername(masterProperties.getUsername());
        dataSourceMaster.setPassword(masterProperties.getPassword());

        HikariDataSource dataSourceSlave = new HikariDataSource();
        dataSourceSlave.setJdbcUrl(slaveProperties.getUrl());
        dataSourceSlave.setUsername(slaveProperties.getUsername());
        dataSourceSlave.setPassword(slaveProperties.getPassword());

        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DatabaseContextHolder.TYPE_MASTER, dataSourceMaster);
        targetDataSources.put(DatabaseContextHolder.TYPE_SLAVE, dataSourceSlave);
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(targetDataSources);

        return dynamicDataSource;
    }
}
